package com.jetpack.mvvm.lib.binding.viewbind

import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.viewbinding.ViewBinding
import com.jetpack.mvvm.lib.binding.base.FragmentDelegate
import com.jetpack.mvvm.lib.binding.ext.bindMethod
import com.jetpack.mvvm.lib.binding.ext.inflateMethod
import kotlin.reflect.KProperty

class FragmentViewBinding<T : ViewBinding>(
    clazz: Class<T>,
    fragment: Fragment,
) : FragmentDelegate<T>(fragment) {
    private val layoutInflaterMethod = clazz.inflateMethod()
    private val bindViewMethod = clazz.bindMethod()

    override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
        return viewBinding?.run {
            return this
        } ?: let {
            try {
                check(thisRef.viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) {
                    "cannot use binding in before onCreateView() or after onDestroyView()"
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            val bind: T = if (thisRef.view == null) {
                // 这里为了兼容在 navigation 中使用 Fragment
                layoutInflaterMethod.invoke(null, thisRef.layoutInflater) as T
            } else {
                bindViewMethod.invoke(null, thisRef.view) as T
            }

            return bind.apply { viewBinding = this }
        }
    }
}